package org.ilead.iserve.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.ilead.iserve.constants.CookiesKeyConstant;
import org.ilead.iserve.constants.SessionKeyConstant;
import org.ilead.iserve.model.User;
import org.ilead.iserve.service.manager.UserManager;
import org.ilead.iserve.util.UrlEncodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mysql.jdbc.StringUtils;

/**
 * 用户登录的过滤器
 * @author jill
 *
 */
public class LoginFilter implements Filter {
	private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		String servletPath = request.getServletPath();
        HttpServletResponse response = (HttpServletResponse)arg1;
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(SessionKeyConstant.LOGIN_USER);
        if(user == null && CookiesHelper.hasCookie(request, CookiesKeyConstant.LOP_AUOT_LOGIN_FLAG)){
        	String username = CookiesHelper.getCookieValueByName(request, CookiesKeyConstant.LOP_LOGIN_NAME);
        	String password = CookiesHelper.getCookieValueByName(request, CookiesKeyConstant.LOP_LOGIN_PASSWORD);
        	if(!StringUtils.isNullOrEmpty(username) && !StringUtils.isNullOrEmpty(password))
        		user = UserManager.getInstance().login(username, password);
        	if(user != null && user.getPermission() > 1){
        		try {
					UserManager.getInstance().updateSessionAndUser(request, user);
				} catch (Exception e) {
					log.error("更新用户信息失败.",e);
				}
        	}else{
        		CookiesHelper.clearUserCookies(request, response);
        		session.removeAttribute(SessionKeyConstant.LOGIN_USER);
        	}
        }
        
        
        if(servletPath != null && UrlEncodeUtil.hasEncode(servletPath)){
	        String lastAccessPage = UrlEncodeUtil.decode(servletPath);
	        session.setAttribute(SessionKeyConstant.LAST_ACCESS_PAGE, lastAccessPage);
	        if(user == null){
	            response.sendRedirect(request.getContextPath() + "/login.jsp");
	            return ;
	        }
        }
        
        String url = request.getContextPath() + servletPath;
//        int permission = LoginFilterRegister.getPermission(url);
//        if(permission > 0 && (user == null || user.getPermission().intValue() < permission)){
//        	session.setAttribute(SessionKeyConstant.LAST_ACCESS_PAGE, url);
//        	response.sendRedirect(request.getContextPath() + "/login.jsp");
//        	return;
//        }
        //若用户已经登录，再访问login.jsp或register.jsp页面，直接跳到首页
        Object lastPageObj = session.getAttribute(SessionKeyConstant.LAST_ACCESS_PAGE);
        String lastPage = lastPageObj != null ? lastPageObj.toString() : request.getContextPath() + "/index.jsp";
        if(user != null && isLoginOrRegisterPage(url)){
        	response.sendRedirect(lastPage);
        }
        filterChain.doFilter(arg0, arg1);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
	private boolean isLoginOrRegisterPage(String path){
		return path.indexOf("login.jsp") != -1 || path.indexOf("register.jsp") != -1; 
	}

}
